

package com.pig4cloud.pig.common.data.handler;

import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.StrUtil;
import com.pig4cloud.pig.admin.api.entity.SysDeptRelation;
import com.pig4cloud.pig.admin.api.entity.SysRole;
import com.pig4cloud.pig.admin.api.feign.RemoteDataScopeService;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.data.enums.DataScopeTypeEnum;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lengleng
 * @date 2019-09-07
 * <p>
 * 默认data scope 判断处理器
 */
public class PigDefaultDatascopeHandle implements DataScopeHandle {
	@Autowired
	private RemoteDataScopeService dataScopeService;

	/**
	 * 计算用户数据权限
	 *
	 * @param deptList
	 * @return
	 */
	@Override
	public Boolean calcScope(List<Integer> deptList) {

		PigUser user = SecurityUtils.getUser();

		List<String> roleIdList = user.getAuthorities()
				.parallelStream().map(GrantedAuthority::getAuthority)
				.filter(authority -> authority.startsWith(SecurityConstants.ROLE))
				.map(authority -> authority.split(StrUtil.UNDERLINE)[1])
				.collect(Collectors.toList());

		SysRole role = dataScopeService.getRoleList(roleIdList).getData().stream().min(Comparator.comparingInt(SysRole::getDsType)).get();

		List<Integer> deptIdList = dataScopeService.getDescendantList(user.getDeptId()).getData().parallelStream()
				.map(SysDeptRelation::getDescendant).collect(Collectors.toList());

		DataScopeTypeEnum dataScopeTypeEnum = EnumUtil.fromString(DataScopeTypeEnum.class, String.valueOf(role.getDsType()));
		// Integer dsType = role.getDsType();
/*		// 查询全部
		if (DataScopeTypeEnum.ALL.getType() == dsType) {
			return true;
		}
		// 自定义
		if (DataScopeTypeEnum.CUSTOM.getType() == dsType) {
			String dsScope = role.getDsScope();
			deptList.addAll(Arrays.stream(dsScope.split(StrUtil.COMMA))
					.map(Integer::parseInt).collect(Collectors.toList()));
		}
		// 查询本级及其下级
		if (DataScopeTypeEnum.OWN_CHILD_LEVEL.getType() == dsType) {
			List<Integer> deptIdList = dataScopeService.getDescendantList(user.getDeptId())
					.getData().stream().map(SysDeptRelation::getDescendant)
					.collect(Collectors.toList());
			deptList.addAll(deptIdList);
		}
		// 只查询本级
		if (DataScopeTypeEnum.OWN_LEVEL.getType() == dsType) {
			deptList.add(user.getDeptId());
		}*/
		return dataScopeTypeEnum.calcScope(deptList,deptIdList,role,user);
	}
}
